package com.tkx.dxb.service.article.controller.api;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tkx.dxb.common.base.result.R;
import com.tkx.dxb.service.article.entity.Post;
import com.tkx.dxb.service.article.service.PostService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author victor
 * @since 2021-04-07
 */
@Api(tags = "文章")
@RestController
@RequestMapping("/api/article/post")
public class ApiPostController {
    private PostService postService;

    @Autowired
    public void setTeacherService(PostService postService){
        this.postService = postService;
    }

    @ApiOperation("客户端文章分页列表")
    @GetMapping("list/{page}/{limit}")
    public R listPage(
            @ApiParam(value = "当前页码", required = true) @PathVariable Long page,
            @ApiParam(value = "每页记录数", required = true) @PathVariable Long limit) {
        Page<Post> pageParam = new Page<>(page, limit);
        IPage<Post> pageModel = postService.selectWebPage(pageParam);
        /**
         * getRecords 获取数据
         * getTotal   获取总页数
         */
        List<Post> records = pageModel.getRecords();
        long total = pageModel.getTotal();
        return R.ok().data("total", total).data("rows", records);
    }

    @ApiOperation("客户端热门文章")
    @GetMapping("hotArticle")
    public R hotArticle() {
        /**
         * 获取前十条热门文章
         */
        List<Post> postList = postService.selectHotArticle();
        return R.ok().data("postList",postList);
    }

    @ApiOperation("文章详情")
    @GetMapping("details/{id}")
    public R getArticleById(
            @ApiParam(value = "文章id", required = true) @PathVariable String id) {
        Post post = postService.selectById(id);
        post.setTitleRead(post.getTitleRead() + 1);
        postService.updateById(post);
        return R.ok().data("info", post);
    }

    @ApiOperation("点赞+1")
    @PutMapping("update-titleLike")
    public R updateById(@ApiParam("讲师对象") @RequestBody Post post){
        boolean result = postService.updateById(post);
        if (result){
            return R.ok().message("修改成功");
        }else{
            return R.error().message("数据不存在");
        }
    }
}

